package cn.IT.Nf.Test.Filte;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
public class Filters implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // 设置跨域响应头
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");  // 可以替换为指定域名以增加安全性
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");  // 支持的HTTP方法
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type");  // 允许的请求头
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");  // 允许带有凭证的请求（如果需要）

        // 处理OPTIONS请求（浏览器发出的预检请求）
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) request).getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);  // 返回200状态码表示预检请求成功
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }
}